<?php

namespace App\Http\Controllers\Api\v1;

use App\Activity;
use App\ClickLog;
use App\Http\Controllers\Controller;
use App\SendLog;
use App\SendOrder;
use App\ShareLog;
use App\Siphonlog;
use App\Support\User;
use App\WxUser;
use Illuminate\Http\Request;

class ActivityController extends Controller {
	protected $sendLog, $sendOrder, $user;

	public function __construct(SendLog $sendLog, SendOrder $sendOrder, User $user) {
		$this->sendLog = $sendLog;
		$this->sendOrder = $sendOrder;
		$this->user = $user;
	}

	public function shareCallBack(Request $request) {
		$user_id = $request->input('user_id');
		$unique = $request->input('unique');
		if (!$user_id || !$unique) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$sendLog = $this->sendLog->where('unique', $unique)->where('send_id', $user_id)->where('expore_time', '>', date('Y-m-d H:i:s'))->first();

		if (!$sendLog) {
			return ['code' => 1, 'msg' => 'error unique'];
		}
		$log = ['six_id' => $user_id, 'map_id' => $sendLog->order->map_id];
		(new ShareLog)->create($log);
		return ['code' => 0, 'msg' => 'success'];
	}
	public function shareClickBack(Request $request) {
		$unique = $request->input('unique');
		if (!$unique) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$sendLog = (new SendLog)->where('unique', $unique)->firstOrFail();
		$click = ['six_id' => $sendLog->send_id, 'map_id' => $sendLog->order->map_id];
		(new ClickLog)->create($click);
		return ['code' => 0, 'msg' => 'success'];
	}

	public function setAddress(Request $request) {
		$unique = $request->get('unique');
		$open_id = $request->get('open_id');
		if (!$unique || !$open_id) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$user = (new WxUser)->where('open_id', $open_id)->firstOrFail();
		$share = (new SendLog)->where('unique', $unique)->with('wxUser')->firstOrFail();
		if (!$share->wxUser || $share->wxUser->open_id != $open_id) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$order = (new SendOrder)->where('log_id', $share->id)->firstOrFail();
		$this->validate($request, [
			'contacts' => 'required',
			'phone' => 'required',
			'receipt_area' => 'required',
			'receipt_address' => 'required',
		]);
		$order->contacts = $request->contacts;
		$order->phone = $request->phone;
		$order->receipt_area = $request->receipt_area;
		$order->receipt_address = $request->receipt_address;
		$order->save();
		$content = '恭喜你免费获得' . $order->products . '！正在等待商家发货~（点击查看详情）';
		$this->user->sendNotice($user->six_id, $order->id, '中奖通知', $content);

		return ['code' => 0, 'msg' => 'success'];
	}

	public function detail(Request $request) {
		$id = $request->input('id');
		if (!$id || !is_numeric($id)) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$data = $this->sendOrder->where('id', $id)->first();
		if (!$data) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$this->user->setMsgRead($data->user_id, $data->id);
		return ['code' => 0, 'msg' => 'success', 'data' => $data];
	}

	public function index(Request $request) {
		$id = $request->input('user_id');
		if (!$id || !is_numeric($id)) {
			return ['code' => 1, 'msg' => 'error params'];
		}
		$list = $this->sendLog->where('send_id', $id)->with('order')->orderBy('create_time', 'desc')->get();
		$needRedPoint = false;
		$data = [
			'send' => (object) [],
			'accept' => (object) [],
			'list' => [],
		];
		$send = $append_data = [];
		if ($list) {
			foreach ($list as $key => $value) {
				$append_data = [
					'id' => $value->id,
					'unique' => $value->unique,
				];
				$now = date('Y-m-d H:i:s');
				$activity = $value->order->map->activity->toArray();
				unset($activity['updated_at']);
				unset($activity['created_at']);
				$activity['product'] = $value->products;
				if ($value->read == 0) {
					if ($value->expore_time > date('Y-m-d H:i:s')) {
						$send = $activity;
						$send['unique'] = $value->unique;
						$value->read = 1;
						$value->save();
					}
					$needRedPoint = true;
				}
				$activity['created_at'] = $value->create_time;
				$activity['expore_at'] = $value->expore_time;
				$activity['expired'] = $activity['expore_at'] < $now;
				$data['list'][] = array_merge($activity, $append_data);
			}
		}
		if ($send) {
			$data['send'] = $send;
		}
		$accept = $this->sendOrder->where('user_id', $id)->where('status', 0)->where('read', 0)->whereNotNull('contacts')->with('sendLog')->first();
		if ($accept) {
			$data['accept'] = $accept->sendLog->order->map->activity;
			$data['accept']['id'] = $accept->id;
			unset($data['accept']['updated_at']);
			unset($data['accept']['created_at']);
			$accept->read = 1;
			$accept->save();
		}
		$data['needRedPoint'] = $needRedPoint;
		return response(['code' => 200, 'msg' => 'success', 'data' => $data]);
	}

	public function share($unique, $openid) {
		$user = (new WxUser)->where('open_id', $openid)->first();
		$share = (new SendLog)->where('unique', $unique)->withCount('siphons')->with('wxUser')->first();
		$already = !!(new Siphonlog)->where('wx_id', $user->id)->where('sendlog_id', $share->id)->first();
		$sendOrder = (new SendOrder)->where('log_id', $share->id)->where('user_id', $user->six_id)->first();
		if ($user->id == $share->wx_id) {
			$clickTime = (new siphonLog)->where('sendlog_id', $share->id)->where('wx_id', $user->id)->first();
		}
		return compact('user', 'share', 'already', 'sendOrder', 'clickTime');
	}

	public function lottery($unique, $open_id) {
		$share = (new SendLog)->withCount('siphons')->where('unique', $unique)->firstOrFail();
		$user = (new WxUser)->where('open_id', $open_id)->firstOrFail();
		$model = new Siphonlog();
		$msg = "failed";
		$already_lottery = $model->where('wx_id', $user->id)->where('sendlog_id', $share->id)->first();
		if ($already_lottery) {
			return ['code' => 0, 'msg' => 'already'];
		}
		$result = $this->dealLottery($share->nums, $share->siphons_count, $share->win);
		if ($result > 0 && $result == $share->win) {
			$share->wx_id = $user->id;
			$share->save();
			$msg = 'success';
		}
		$model->create(['sendlog_id' => $share->id, 'map_id' => $share->order->map_id, 'wx_id' => $user->id, 'create_time' => date('Y-m-d H:i:s'), 'expore_time' => date('Y-m-d H:i:s', strtotime('+1 day'))]);
		return ['code' => 0, 'msg' => $msg];
	}

	private function dealLottery($num, $clickNum, $successNum) {
		if ($clickNum >= $num) {
			return 0;
		}
		$offset = floor(($num - $clickNum) / 2);
		$start = $successNum - $offset > 1 ? $successNum - $offset : 1;
		$end = $num - $clickNum - 1 + $start;
		if ($end > $num) {
			$end = $num;
			$start = $end - ($num - $clickNum - 1);
		}
		return rand($start, $end);
	}
}
